package com.laicunba.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.laicunba.service.MobileMessageService;
import com.laicunba.util.ThreadUtil;

 
public class MobileMessageServiceYXImpl implements MobileMessageService {
	private static final Logger LOG = Logger.getLogger(MobileMessageServiceYXImpl.class);

	@Value("${mobile.msg.yx.url}")
	private String url;
	@Value("${mobile.msg.yx.username}")
	private String username;
	@Value("${mobile.msg.yx.pswd}")
	private String pswd;
	@Value("${mobile.msg.yx.encode}")
	private String encode;
	@Value("${mobile.msg.yx.mock}")
	private boolean mock;

	@Override
	public void sendMsgAsync(final String mobile, final String msg) {
		if (mock) {
			LOG.warn(String.format("短信未发送警告(由于 mock被设置为true)  手机号码:%s ,短信内容: %s", mobile, msg));
			return;
		}
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				HttpURLConnection conn = null;
				try {
					// 组建请求
					String straddr = url + "?uid=" + username + "&pwd=" + pswd + "&mobile="
							+ mobile + "&encode=" + encode + "&content="
							+ URLEncoder.encode(msg, "UTF-8");
					StringBuffer sb = new StringBuffer(straddr);
					System.out.println("URL:" + sb);

					// 发送请求
					URL url = new URL(sb.toString());
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("POST");
					BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

					// 返回结果
					String inputline = in.readLine();
					System.out.println("Response:" + inputline);
					LOG.info(String.format("发送短信完毕  手机号[%s],内容[%s],发送结果[%s]", mobile, msg, inputline));
				} catch (Exception e) {
					LOG.error("短信发送异常", e);
				} finally {
					conn.disconnect();
				}
			}
		});
	}

	@Override
	public void sendMsgAsyncByAlidayu(String templateCode,String mobile, JSONObject param) {
		// TODO Auto-generated method stub
		
	}

}
